/**
 * 订单报表公用工具
 * @author hankangshuai
 * @since 2019-11-15
 */
class ReportUtil {
    /**
     * layui表格工具栏右侧增加按钮（在表格的done方法中使用,否则表格reload会失效）
     * @param layout  数组  示例：[{title: '导出', layEvent: 'CUSTOM_EXPORT', icon: 'layui-icon-export', display: true}...]  display属性默认true,传false隐藏
     * @author hankangshuai
     */
    static toobarRightAddButton(layout) {
        let iconElem = [];
        layout.filter((i, v) => i.display || i.display === undefined).forEach((item, index, array) => {
            iconElem.push('<div class="layui-inline" title="' + item.title + '" lay-event="' + item.layEvent + '">'
                + '<i class="layui-icon ' + item.icon + '"></i>'
                + '</div>');
        });
        //  替换容器内容
        document.querySelector('.layui-table-tool-self').innerHTML = iconElem.join('');
    }

    /**
     * 切换按钮图标到加载（loading图标旋转并且会添加禁用鼠标样式）
     * @param element  要切换的图标DOM(一般是i元素)
     * @author hankangshuai
     * @since 2019-7-17
     */
    static toggleLoading(element) {
        let isLoading = element.className === 'layui-disabled layui-icon layui-icon-loading-1 layui-anim layui-anim-loop layui-anim-rotate';
        if (isLoading && element.attributes['icon-class-cache']) {
            element.className = element.attributes['icon-class-cache'].value;
        } else {
            element.setAttribute("icon-class-cache", element.className);
            element.className = 'layui-disabled layui-icon layui-icon-loading-1 layui-anim layui-anim-loop layui-anim-rotate';
        }
    }


    /**
     * 封装的tips，适配laytable的配色，点击提示框外会关闭提示（layer.tips无法点击空白处隐藏tips）
     * @param html 提示内容
     * @param ele 绑定对象
     */
    static tips(html, ele) {
        let style = document.createElement("style");
        style.appendChild(document.createTextNode("    /*帮助提示框*/\n" +
            "    body .zmn-tips {\n" +
            "\n" +
            "    }\n" +
            "\n" +
            "    body .zmn-tips .layui-layer-content {\n" +
            "        color: #0C0C0C;\n" +
            "        background-color: #e6e6e6;\n" +
            "        padding-right: 3px;\n" +
            "        width: 396px;\n" +
            "        height: 300px;\n" +
            "        overflow-x: hidden;\n" +
            "        overflow-y: scroll;\n" +
            "    }\n" +
            "\n" +
            "    body .zmn-tips .layui-layer-content::-webkit-scrollbar-track {\n" +
            "        background-color: #e6b31a;\n" +
            "    }\n" +
            "\n" +
            "    body i.layui-layer-TipsB, i.layui-layer-TipsT, i.layui-layer-TipsL, i.layui-layer-TipsR, i.layui-layer-TipsG {\n" +
            "        border-right-color: #e6e6e6;\n" +
            "    }\n" +
            "\n" +
            "    body .layui-layer-tips i.layui-layer-TipsB, .layui-layer-tips i.layui-layer-TipsT {\n" +
            "        border-right-color: #e6e6e6;\n" +
            "    }"));
        let head = document.getElementsByTagName("head")[0];
        head.appendChild(style);
        layui.layer.open({
            type: 4
            , closeBtn: false
            , shade: 0.0001
            , tips: 1
            , skin: 'zmn-tips'
            , shadeClose: true
            , content: [html, ele]
        });
    }

    /**
     * 表格头部渲染一行总计行,动态渲染需在done函数中执行，否则表格重载会失效
     * @param extData 数据，内容与表格渲染中的单条数据一致,不需要任何处理，会调用cols里的templet处理；
     */
    static renderTotalRow(extData) {
        //数据为空退出渲染
        if (!extData) {
            return;
        }
        //如果页面已有总计行,退出
        if (document.querySelector('.layui-table-header').querySelectorAll('tr').length > 1) {
            return;
        }
        // 调用各列的templet处理原始统计行数据
        if (layui && layui.table) {
            let id = document.querySelector('.layui-form.layui-border-box.layui-table-view').getAttribute('lay-id')
            layui.table.eachCols(id, function (i, item) {
                if (item.templet) {
                    extData[item.field] = item.templet(extData);
                }
            })
        }
        let getHtml = (fields, extData, needPatch) => {
            let ths = fields.map((item) => `<th data-field="${item}"><div class="layui-table-cell" align="center"><span>${extData[item] === undefined ? "" : extData[item]}</span></div></th>`)
                .reduce((sum, cul) => sum + cul);
            let patch = '<th class="layui-table-patch"><div class="layui-table-cell" style="width: 17px;"></div></th>'
            return `<tr>${ths}${needPatch ? patch : ''}</tr>`;
        };
        //渲染非固定列Field;
        let fields = Array.prototype.slice.call(document.querySelector('.layui-table-header ')
            .querySelectorAll('th'))
            .filter(value => value.className === '')
            .map((item) => item.getAttribute('data-field'));
        document.querySelector('.layui-table-header thead').innerHTML += getHtml(fields, extData, true);
        //容器减少一栏高度
        let elementNodeListOf = document.querySelectorAll('.layui-table-body');
        elementNodeListOf[0].style.height = parseInt(elementNodeListOf[0].style.height) - 35 + 'px';
        //渲染固定列field;
        let fixFields = Array.prototype.slice.call(document.querySelectorAll('.layui-table-fixed .layui-table-header th')).map((item) => item.getAttribute('data-field'));
        if (fixFields.length > 0) {
            document.querySelector('.layui-table-fixed .layui-table-header thead').innerHTML += getHtml(fixFields, extData, false);
            //固定行需要多减滚动条的高度
            elementNodeListOf[1].style.height = parseInt(elementNodeListOf[0].style.height) - 17 + 'px';
        }
    }

    /**
     * 支持回调的下载文件简易封装（使用了html5特性，不支持古董浏览器）
     * @param url  地址
     * @param param 参数
     * @param fileName 文件名
     * @param done 下载完成的回调
     * @author hankangshuai
     * @since 2019-7-17
     */
    static download(url, param, fileName = new Date().toISOString(), done = () => {
    }) {
        new URLSearchParams()
        fetch(url + '?' + new URLSearchParams(param).toString(), {
            credentials: 'include'
        }).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = fileName;
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            done(blob);
        }));
    }
}

